package com.trippin.Utils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;

import com.trippin.server.TrippinDateTime;


public class TimeUtil {
	
	public static void timeValidator(int numOfDays, Date start, Date end, boolean allowNulls) throws IOException {
		if(numOfDays > 0) {
			if(start != null && end != null) {
				long diff = end.getTime() - start.getTime();
				if(numOfDays != (int)(diff / 86400000)) {
					throw new IOException("numOfDays must be equal to (end - start)");
				}				
			}
			else if(start != null || end != null) {
				throw new IOException("user must define a start and end dates or a number of days");
			}
		}		
		else if(numOfDays <= 0) {
			if((start == null) && (end == null) && allowNulls) {
				return;
			}
			else if((start == null) || (end == null)) {
				throw new IOException("user must define a start and end dates or a number of days");
			}
			else if(start.after(end)) {
				throw new IOException("start Date must be before end Date");
			}
			
		}
	}

	public static Calendar parseToDate(String dateString) throws ServletException {
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm Z");
		try {
			Date date = sdf.parse(dateString);
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			return cal;
		} catch (ParseException e) {
			throw new ServletException("Date format is invalid: " + dateString + "correct format is: dd/MM/yyyy HH:mm Z");
		}
	}
	
	
	public static String parseFromDate(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm Z");
		return sdf.format(date);

	}
	
	/**
	 * 
	 * @param dateTime - in the format of DD/MM/YYYY HH:MM ZZZ (ZZZ === GMT time e.g +01)
	 * @return if the dateTime string match the format it return a TrippinDateTime object represent that data time, 
	 * else it returns null
	 */
	public static TrippinDateTime convertToTrippinDateTime(String dateTime) {
		if(dateTime == null)
			return null;
		
		String trimmed = dateTime.trim();
		String[] dateTimeArr = trimmed.split("[ ]+");		
		if(dateTimeArr.length != 3)
			return null;
		
		String[] data = dateTimeArr[0].split("/");		
		if(data.length != 3)
			return null;
		
		String[] time = dateTimeArr[1].split(":");
		if(time.length != 2)
			return null;
		
		int day = Integer.parseInt(data[0]);
		int month = Integer.parseInt(data[1]);
		int year = Integer.parseInt(data[2]);
		int hourOfDay = Integer.parseInt(time[0]);
		int minutes = Integer.parseInt(time[1]);
		int gmt = Integer.parseInt(dateTimeArr[2]);
		
		return new TrippinDateTime(year, month, day, hourOfDay, minutes,gmt);
		
	}

}
